package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.HttpConnectionUtil
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import cn.com.kh.LogToDB
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat

/**
 * @projectName: ngsapitask-pa
 * @package: cn.com.callback* @className: apiDealKafkaMsg* @author: LiJT* @description: 企微数据回调处理主接口* @date: 2022-07-12 11:51
 * @version: 1.0
 */
public class apiDealKafkaMsg implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiDealKafkaMsg.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");

        // 调用IP过滤
        if (KHDBConfig.getParam(eliteBean, "#APIIP") == "1" && !KHUtil.getRemoteHost(request)) {
            log.warn("API被非法IP调用-Request Not Allow!");
            return "非法IP调用 Request Not Allow!";
        } else {
        }

        long startTime = System.currentTimeMillis();

        String rec_Guid = String.valueOf(startTime) + "_" + KHUtil.getRandomString(8).toUpperCase();

        // 初始化返回参数
        JSONObject result = new JSONObject();

        // 获取接口调用方式及参数
        String getMethod = request.getMethod();
        log.debug("[getMethod]:" + getMethod);

        String inData = "";
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("[原始Get请求参数]:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("[原始Post请求参数]:" + inData);
        }
        log.info("[调用请求信息]:" + inData);

        try {
            //解析Json
            JSONObject inJson = JSONObject.fromObject(inData);

            if (inJson.getInt("code") != 1) {
                result.put("code", -1);
                result.put("msg", "接口数据code异常放弃处理");
            } else {

                // 如果系统参数配置为API处理则不使用多线程
                JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
                String threadSQL = '''Insert Into Elitethread
                                              (Thread_Guid, Createdate, Status, Content, Type, Expand)
                                            Values
                                              (Uuid(), Now(), '0', ?, 'autoDealKafkaThread', Date_Format(current_timestamp(6), '%Y-%m-%d %H:%i:%s.%f'))''';
                int threadSQLRes = jt.update(threadSQL, rec_Guid);
                log.debug("当前请求数据放入线程表处理-:" + threadSQLRes);

                result.put("code", 1);
                result.put("msg", "SUCC");
            }
        } catch (Exception e) {
            log.error("", e);
            result.put("code", 1006);
            result.put("msg", "数据处理错误");
        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "内部调用", "apiDealKafkaMsg", inData.replaceAll("'", "''").replaceAll("@","").replaceAll("¥",""), result.toString(), (System.currentTimeMillis() - startTime).toString(), rec_Guid);
        }

        return result.toString();
    }
}